<?php namespace Admin\Model;
use Hdphp\Model\Model;

class Goods extends Model{
	//指定表名,固定写法
    protected $table = "goods";
	
	private static $gid;
	//自动验证,固定写法
	protected $validate = array(
		array('gname','required','名称不能为空',3,3),
		array('category_cid','required','分类必须选择',3,3),
		array('brand_bid','required','品牌必须选择',3,3)
	);
	//自动完成
	protected $auto = array(
		//查手册
		//3是必须处理的表单，1是在插入时候处理
	 	array('gtime','time','function',3,1),
	 	array('administrator_aid','administrator','method',3,1),
	 	array('gnum','gnum','method',4,1),
	 	array('type_tid','type_tid','method',3,1),
	);
	
	//处理字段administrator_aid的方法，该方法返回什么，数据库就可以存入什么
	public function administrator(){
		return $_SESSION['aid'];
	}
	//货号为空时 自动返回随机数
	public function gnum(){
		$gnum = 'N'.mt_rand(0,9).time();
		return $gnum;
	}

	public function type_tid(){
		if(IS_POST){
			$category_cid = Q('post.category_cid',0,'intval');
			$categorydata = Db::table('category')->where("cid={$category_cid}")->get();
			foreach($categorydata as $v){
				$data = $v['type_tid'];
			}
			return $data;
		}
	}
	
	//添加
	public function store(){
		//一.触发三张表的自动验证
		//1.验证goods
		if(!$this->create()) return false;
		//如果上传失败
		if($error = Upload::getError()){
			//给当前模型压入错误
			$this->error = $error;
			return false;
		}
		//2.验证goodsdes
		$goodsdesModel = new \Admin\Model\Goodsdes;
		if(!$goodsdesModel->create()){
			//把goodsdes模型的错误，压到当前模型
			$this->error = $goodsdesModel->getError();
			return false;
		}
		
		//二、添加数据
		//1.goods表，返回自增id
		self::$gid = $this->add();
		//2.数据表
		//给goodsdes表 加上goods_gid 让他们联系起来
		$desdata = array();
		if(IS_POST){
			$img =  implode(',',Q('post.gdpic',array()));
			$desdata = array(
				'gdpic'=>$img,
				'gdcontent'=>Q('post.gdcontent',''),
				'gdaft'=>Q('post.gdaft',''),
				'goods_gid'=>self::$gid,
			);
			$goodsdesModel->add($desdata);
		}
		
		//3.goodsattr
		$goodsattrModel = new \Admin\Model\Goodsattr;
//		循环提取规格和附加值
		foreach	(Q('post.spec',array()) as $k => $v){
			$data['typeattr_taid'] = $k;
			$data['goods_gid'] = self::$gid;
			foreach ($v as $key => $value) {
				if($key=='value'){
					$data['gavalue'] = implode(',', $value);
				}
				if($key=='price'){
					foreach ($value as $ke => $va) {
						if(!$va){
							$va = 0;
							$value[$ke] = $va;
						} 
					}
					$data['gaadd'] = implode(',', $value);
				}
			}
			$goodsattrModel->add($data);
		}
//		循环提取属性
		foreach	(Q('post.attr',array()) as $k => $v){
			$data2 = array(
				'gavalue'=>$v,
				'typeattr_taid'=>$k,
			);
			$data2['goods_gid'] = self::$gid;
			$goodsattrModel->add($data2);
		}
		
		return true;
		
	}
	
	
	 
}







